package br.diego.tb.simpleloops;


public class LongestPalindrome 
{
	public static String longest_palindrome(String s)
	{
		if(s == null || s.isEmpty())
		{
			System.out.println("");
			return "";
		}
		
		if(s.length() <= 3)
		{
			return (s.charAt(0) == s.charAt(s.length() - 1)) ? s : "";
		}
			
		String longestPalindrome = findLongestPalindrome(s);
		
		return longestPalindrome;
	}

	private static String findLongestPalindrome(String s)
	{
		String longestPalindrome = "";
		String candidate = "";
		
		for(int centralCharPosition = 1; centralCharPosition < s.length(); centralCharPosition ++)
		{
			for(int offset = 1; offset <= centralCharPosition ; offset ++)
			{
				int beforePosition = centralCharPosition - offset;
				int afterPosition = centralCharPosition + offset;
				
				if(afterPosition >= s.length())
				{
					//Went too damn far! We can't check for a char which is not in the string, can we? :P
					break;
				}
				
				char beforeCentral = s.charAt(beforePosition);
				char centralChar = s.charAt(centralCharPosition);
				char afterCentral = s.charAt(afterPosition);
				
				if(beforeCentral == afterCentral)
				{
					candidate = s.substring(beforePosition, afterPosition + 1); 
				}
				else
				{
					// Like in abba, when current char is the second b, we want to compare
                    // the next letters (a to a)
					if(centralChar == beforeCentral)
					{
						if(s.charAt(centralCharPosition - offset - 1) == afterCentral)
						{
							candidate = s.substring(beforePosition - 1, centralCharPosition + offset + 1); 
						}
					}
					else
					{
						break;
					}
						
				}
				
				if(candidate.length() > longestPalindrome.length())
				{
					longestPalindrome = candidate;
				}
			}
				
		}

		return longestPalindrome;
	}
}
